import { createStore, Store, useStore as useVuexStore } from 'vuex'
import login from './modules/login'
import systemModule from './modules/main'
import dashboardStore from './modules/dashboard'
import { RootState, IStoreType } from './types'

import { getPageListData } from '@/api/main/system/system'

const store = createStore<RootState>({
  state: () => ({
    name: 'coderWyc',
    entireDepartment: [],
    entireRole: [],
    entireMenu: []
  }),
  mutations: {
    CHANGE_DEPARTMENT(state, list) {
      state.entireDepartment = list
    },
    CHANGE_ROLE(state, list) {
      state.entireRole = list
    },
    CHANGE_ENTIRE_MENU(state, list) {
      state.entireMenu = list
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // 获取部门列表
      const departmentResult = await getPageListData('/department/list', { offset: 0, size: 1000 })
      const { list: departmentList } = departmentResult.data
      // 获取角色列表
      const roleResult = await getPageListData('/role/list', { offset: 0, size: 1000 })
      const { list: roleList } = roleResult.data

      // 获取角色权限数据
      const menuResult = await getPageListData('/menu/list', { offset: 0, size: 1000 })
      const { list: menuList } = menuResult.data
      // 保存数据
      commit('CHANGE_DEPARTMENT', departmentList)
      commit('CHANGE_ROLE', roleList)
      commit('CHANGE_ENTIRE_MENU', menuList)
    }
  },
  getters: {},
  modules: {
    login,
    system: systemModule,
    dashboard: dashboardStore
  }
})
export function setupStore() {
  store.dispatch('login/locadLocalLogin')
  // store.dispatch('getInitialDataAction')
}
export function useStore(): Store<IStoreType> {
  // 将vuex内部useStore封装
  return useVuexStore()
}

export default store
